package com.hospital.KT_Activity;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Html;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.*;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener2;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.hospital.activity.R;
import com.hospital.adapter.DoctorListAdapter;
import com.hospital.view.DropDownView.DropdownButton;
import com.hospital.view.DropDownView.DropdownItemObject;
import com.hospital.view.DropDownView.DropdownListView;
import com.hospital.view.DropDownView.TopicLabelObject;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

public class DoctorListActivity extends Activity {
    private static final int ID_TYPE_ALL = 0;
    private static final int ID_TYPE_MY = 1;
    private static final String TYPE_ALL = "所有地区";
    private static final String TYPE_MY = "鄞州区";

    private static final int ID_LABEL_ALL = -1;
    private static final String LABEL_ALL = "所有医院";

    private static final String ORDER_REPLY_TIME = "所有科室";
    private static final String ORDER_PUBLISH_TIME = "内科";
    private static final String ORDER_HOT = "外科";
    private static final int ID_ORDER_REPLY_TIME = 51;
    private static final int ID_ORDER_PUBLISH_TIME = 49;
    private static final int ID_ORDER_HOT = 53;

    PullToRefreshListView mPullToRefreshListView;
    View mask;
    DropdownButton chooseType, chooseLabel, chooseOrder;
    DropdownListView dropdownType, dropdownLabel, dropdownOrder;
    LinearLayout head_back;

    Animation dropdown_in, dropdown_out, dropdown_mask_out;

    TextView head_title,tv_back;
    ImageView iv_back;



    private List<TopicLabelObject> labels = new ArrayList<>();

    private DropdownButtonsController dropdownButtonsController = new DropdownButtonsController();
    
    private DoctorListAdapter doctorListAdapter;

    private View searchview;

    int screen_width = 0;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.doctor_list);

        mPullToRefreshListView = (PullToRefreshListView) findViewById(R.id.listView);
        mask = findViewById(R.id.mask);
        chooseType = (DropdownButton) findViewById(R.id.chooseType);
        chooseLabel = (DropdownButton) findViewById(R.id.chooseLabel);
        chooseOrder = (DropdownButton) findViewById(R.id.chooseOrder);
        dropdownType = (DropdownListView) findViewById(R.id.dropdownType);
        dropdownLabel = (DropdownListView) findViewById(R.id.dropdownLabel);
        dropdownOrder = (DropdownListView) findViewById(R.id.dropdownOrder);
        head_back = (LinearLayout)findViewById(R.id.head_back);
        head_title = (TextView)findViewById(R.id.head_title);
        tv_back = (TextView)findViewById(R.id.tv_back);
        iv_back = (ImageView)findViewById(R.id.iv_back);


        dropdown_in = AnimationUtils.loadAnimation(this,R.anim.dropdown_in);
        dropdown_out = AnimationUtils.loadAnimation(this,R.anim.dropdown_out);
        dropdown_mask_out = AnimationUtils.loadAnimation(this,R.anim.dropdown_mask_out);

        dropdownButtonsController.init();

        //id count name
        TopicLabelObject topicLabelObject1 =  new TopicLabelObject(1,1,"鄞州人民医院");
        labels.add(topicLabelObject1);
        TopicLabelObject topicLabelObject2 =new TopicLabelObject(2,1,"鄞州第二医院");
        labels.add(topicLabelObject2);
        TopicLabelObject topicLabelObject3 =new TopicLabelObject(2,1,"鄞州第三医院");
        labels.add(topicLabelObject3);
        TopicLabelObject topicLabelObject4 =new TopicLabelObject(2,1,"鄞州第四医院");
        labels.add(topicLabelObject4);
        TopicLabelObject topicLabelObject5 =new TopicLabelObject(2,1,"鄞州第五医院");
        labels.add(topicLabelObject5);

        mask.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dropdownButtonsController.hide();
            }
        });
        head_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });


        dropdownButtonsController.flushCounts();
        dropdownButtonsController.flushAllLabels();
        dropdownButtonsController.flushMyLabels();

        mPullToRefreshListView.setMode(Mode.BOTH);
        mPullToRefreshListView.setOnRefreshListener(new OnRefreshListener2<ListView>(){
        	   
            // 下拉Pulling Down  
            @Override  
            public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {  
                // 下拉的时候数据重置  
               
                new PullingDownRefresh().execute();  
            }  
              
            // 上拉Pulling Up  
            @Override  
            public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {  
                // 上拉的时候添加选项  
               
                new PullingUpRefresh().execute();  
            }  
   
        });  
          
        
        ListView actualListView = mPullToRefreshListView.getRefreshableView();
        doctorListAdapter = new DoctorListAdapter(DoctorListActivity.this, R.layout.doctor_list_item);
        actualListView.setAdapter(doctorListAdapter);

        actualListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                Intent doctorIntroductionIntent = new Intent(DoctorListActivity.this,DoctorIntroductionActivity.class);
                startActivity(doctorIntroductionIntent);
            }
        });

        //获取iv_back的宽度
        ViewGroup.LayoutParams lp  = iv_back.getLayoutParams();

        //获取屏幕宽高
        DisplayMetrics dm = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(dm);
        screen_width = dm.widthPixels;

        //SearchView
        SearchView search = (SearchView)findViewById(R.id.searchView1);
        //search.setIconifiedByDefault(false);
        //search.setSubmitButtonEnabled(true);
        //改变SearchView输入文字颜色
        int id = search.getContext().getResources().getIdentifier("android:id/search_src_text", null, null);
        TextView textView = (TextView) search.findViewById(id);
        textView.setTextColor(Color.WHITE);

        //设置提示文字的颜色,这里走了点奇招,用Html类方法
        search.setQueryHint(Html.fromHtml("<font color = #ffffff>" + getResources().getString(R.string.search_value) + "</font>"));
        //修改最大宽度
        search.setMaxWidth(screen_width-lp.width);
        //修改搜索图标
        try{
            Class<?> argClass=search.getClass();
            Field mSearchButton = argClass.getDeclaredField("mSearchButton");
            mSearchButton.setAccessible(true);
            ImageView searchImg = (ImageView) mSearchButton.get(search);
            searchImg.setImageResource(R.drawable.sy13);
        } catch(Exception e){

        }



        search.setOnSearchClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ClearHeader(true);
                if(searchview==null){
                    searchview = view ;
                }
                ViewGroup.LayoutParams para = view.getLayoutParams();
                para.height =94;
                view.setLayoutParams(para);
            }
        });

        search.setOnCloseListener(new SearchView.OnCloseListener() {
            @Override
            public boolean onClose() {
                ClearHeader(false);
                if(searchview!=null) {
                    ViewGroup.LayoutParams para = searchview.getLayoutParams();
                    para.height = 40;
                    searchview.setLayoutParams(para);
                }
                return false;
            }
        });


        search.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query) {
                return true;
            }

            @Override
            public boolean onQueryTextChange(String newText) {
                return true;
            }
        });
    }

    private void ClearHeader(boolean flag){
        if(flag){
            head_title.setVisibility(View.INVISIBLE);
            tv_back.setVisibility(View.INVISIBLE);
        }else{
            head_title.setVisibility(View.VISIBLE);
            tv_back.setVisibility(View.VISIBLE);
        }
    }
    
    private class PullingDownRefresh extends AsyncTask<Void, Void, String[]> {

        @Override
        protected String[] doInBackground(Void... params) {
            // Simulates a background job.
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
            }
			return null;
        }
        @Override
        protected void onPostExecute(String[] result) {
        	doctorListAdapter.notifyDataSetChanged();
            
            // Call onRefreshComplete when the list has been refreshed.
            mPullToRefreshListView.onRefreshComplete();
            super.onPostExecute(result);
        }
    }
    
    private class PullingUpRefresh extends AsyncTask<Void, Void, String[]> {

        @Override
        protected String[] doInBackground(Void... params) {
            // Simulates a background job.
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
            }
			return null;
        }
        @Override
        protected void onPostExecute(String[] result) {
        	doctorListAdapter.notifyDataSetChanged();
            
            // Call onRefreshComplete when the list has been refreshed.
            mPullToRefreshListView.onRefreshComplete();
            super.onPostExecute(result);
        }
    }

    private class DropdownButtonsController implements DropdownListView.Container {
        private DropdownListView currentDropdownList;
        private List<DropdownItemObject> datasetType = new ArrayList<>(2);
        private List<DropdownItemObject> datasetAllLabel = new ArrayList<>();
        private List<DropdownItemObject> datasetMyLabel = new ArrayList<>();
        private List<DropdownItemObject> datasetLabel = datasetAllLabel;
        private List<DropdownItemObject> datasetOrder = new ArrayList<>(3);

        @Override
        public void show(DropdownListView view) {
            if (currentDropdownList != null) {
                currentDropdownList.clearAnimation();
                currentDropdownList.startAnimation(dropdown_out);
                currentDropdownList.setVisibility(View.GONE);
                currentDropdownList.button.setChecked(false);
            }
            currentDropdownList = view;
            mask.clearAnimation();
            mask.setVisibility(View.VISIBLE);
            currentDropdownList.clearAnimation();
            currentDropdownList.startAnimation(dropdown_in);
            currentDropdownList.setVisibility(View.VISIBLE);
            currentDropdownList.button.setChecked(true);
        }

        @Override
        public void hide() {
            if (currentDropdownList != null) {
                currentDropdownList.clearAnimation();
                currentDropdownList.startAnimation(dropdown_out);
                currentDropdownList.button.setChecked(false);
                mask.clearAnimation();
                mask.startAnimation(dropdown_mask_out);
            }
            currentDropdownList = null;
        }

        @Override
        public void onSelectionChanged(DropdownListView view) {
            if (view == dropdownType) {
                updateLabels(getCurrentLabels());
            }

        }

        void reset() {
            chooseType.setChecked(false);
            chooseLabel.setChecked(false);
            chooseOrder.setChecked(false);

            dropdownType.setVisibility(View.GONE);
            dropdownLabel.setVisibility(View.GONE);
            dropdownOrder.setVisibility(View.GONE);
            mask.setVisibility(View.GONE);

            dropdownType.clearAnimation();
            dropdownLabel.clearAnimation();
            dropdownOrder.clearAnimation();
            mask.clearAnimation();
        }

        void init() {
            reset();
            datasetType.add(new DropdownItemObject(TYPE_ALL, ID_TYPE_ALL, "all"));
            datasetType.add(new DropdownItemObject(TYPE_MY, ID_TYPE_MY, "my"));

            dropdownType.bind(datasetType, chooseType, this, ID_TYPE_ALL);

            datasetAllLabel.add(new DropdownItemObject(LABEL_ALL, ID_LABEL_ALL, null) {
                @Override
                public String getSuffix() {
                    return dropdownType.current == null ? "" : dropdownType.current.getSuffix();
                }
            });
            datasetMyLabel.add(new DropdownItemObject(LABEL_ALL, ID_LABEL_ALL, null));
            datasetLabel = datasetAllLabel;
            dropdownLabel.bind(datasetLabel, chooseLabel, this, ID_LABEL_ALL);

            datasetOrder.add(new DropdownItemObject(ORDER_REPLY_TIME, ID_ORDER_REPLY_TIME, "51"));
            datasetOrder.add(new DropdownItemObject(ORDER_PUBLISH_TIME, ID_ORDER_PUBLISH_TIME, "49"));
            datasetOrder.add(new DropdownItemObject(ORDER_HOT, ID_ORDER_HOT, "53"));
            dropdownOrder.bind(datasetOrder, chooseOrder, this, ID_ORDER_REPLY_TIME);

            dropdown_mask_out.setAnimationListener(new Animation.AnimationListener() {
                @Override
                public void onAnimationStart(Animation animation) {

                }

                @Override
                public void onAnimationEnd(Animation animation) {
                    if (currentDropdownList == null) {
                        reset();
                    }
                }

                @Override
                public void onAnimationRepeat(Animation animation) {

                }
            });
        }

        private List<DropdownItemObject> getCurrentLabels() {
            return dropdownType.current != null && dropdownType.current.id == ID_TYPE_MY ? datasetMyLabel : datasetAllLabel;
        }

        void updateLabels(List<DropdownItemObject> targetList) {
            if (targetList == getCurrentLabels()) {
                datasetLabel = targetList;
                dropdownLabel.bind(datasetLabel, chooseLabel, this, dropdownLabel.current.id);
            }
        }

        public void flushCounts() {

            datasetType.get(ID_TYPE_ALL).setSuffix(" (" + "5" + ")");
            datasetType.get(ID_TYPE_MY).setSuffix(" (" + "3" + ")");
            dropdownType.flush();
            dropdownLabel.flush();
        }

        void flushAllLabels() {
            flushLabels(datasetAllLabel);
        }

        void flushMyLabels() {
            flushLabels(datasetMyLabel);
        }

        private void flushLabels(List<DropdownItemObject> targetList) {

            while (targetList.size() > 1) targetList.remove(targetList.size() - 1);
            for (int i = 0, n = 5; i < n; i++) {

                int id = labels.get(i).getId();
                String name = labels.get(i).getName();
                if (TextUtils.isEmpty(name)) continue;
                int topicsCount = labels.get(i).getCount();
                // 只有all才做0数量过滤，因为my的返回数据总是0
                if (topicsCount == 0 && targetList == datasetAllLabel) continue;
                DropdownItemObject item = new DropdownItemObject(name, id, String.valueOf(id));
                if (targetList == datasetAllLabel)
                    item.setSuffix("(5)");
                targetList.add(item);
            }
            updateLabels(targetList);
        }
    }
}
